package com.mall.project.sys.service.impl;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.common.core.asserts.ApiAssert;
import com.mall.common.core.cons.StatusCons;
import com.mall.common.core.enums.ErrorCodeEnum;
import com.mall.project.sys.cons.LevelCons;
import com.mall.project.sys.mapper.RoleMapper;
import com.mall.project.sys.model.entity.Menu;
import com.mall.project.sys.model.entity.Role;
import com.mall.project.sys.model.entity.RoleMenu;
import com.mall.project.sys.model.entity.User;
import com.mall.project.sys.model.parm.RolePARM;
import com.mall.project.sys.service.IMenuService;
import com.mall.project.sys.service.IRoleMenuService;
import com.mall.project.sys.service.IRoleService;
import com.mall.project.sys.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.PostConstruct;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <p>
 * 角色表 服务实现类
 * </p>
 *
 * @author Sam
 * @since 2021-04-13
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements IRoleService {

    @Autowired
    private IRoleMenuService roleMenuService;
    @Autowired
    private IMenuService menuService;
    @Autowired
    private IUserService userService;

    /**
     * 超级管理员授权
     */
    @PostConstruct
    public void init() {
        List<Role> adminList = this.list(Wrappers.<Role>lambdaQuery().eq(Role::getLevel, 1));
        if (CollectionUtils.isEmpty(adminList)) {
            return;
        }
        List<Menu> menuList = menuService.list();
        List<String> roleIdList = adminList.stream().map(Role::getId).collect(Collectors.toList());
        List<RoleMenu> addList = new ArrayList<>();
        roleIdList.forEach(roleId -> {
            menuList.forEach(menu -> {
                RoleMenu roleMenu = new RoleMenu();
                roleMenu.setRoleId(roleId);
                roleMenu.setMenuId(menu.getId());
                addList.add(roleMenu);
            });
        });
        if (CollectionUtils.isNotEmpty(roleIdList)) {
            roleMenuService.remove(Wrappers.<RoleMenu>lambdaQuery().in(RoleMenu::getRoleId, roleIdList));
        }
        if (CollectionUtils.isNotEmpty(addList)) {
            roleMenuService.saveBatch(addList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createRole(RolePARM rolePARM) {
        Role role = rolePARM.convert(Role.class);
        ApiAssert.isTrue(ErrorCodeEnum.BAD_ADD_FAILURE, this.save(role));
        assignRole(role.getId(), rolePARM.getMenuIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRole(RolePARM rolePARM) {
        Role role = rolePARM.convert(Role.class);
        ApiAssert.isTrue(ErrorCodeEnum.BAD_UPDATE_FAILURE, this.updateById(role));
        assign(role.getId(), rolePARM.getMenuIdList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void delRole(String roleId) {
        Role role = this.getById(roleId);
        ApiAssert.notNull(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("查不到该角色信息"), role);
        ApiAssert.isFalse(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("管理级别角色不允许删除"), Objects.equals(role.getLevel(), LevelCons.SUPER));
        int count = userService.count(Wrappers.<User>lambdaQuery().eq(User::getRoleId, roleId));
        ApiAssert.isFalse(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("该角色存在绑定用户,不允许删除"), count > 0);
        //删除角色
        Role updateRole = new Role();
        updateRole.setId(roleId);
        updateRole.setStatus(StatusCons.DISABLE);
        ApiAssert.isTrue(ErrorCodeEnum.BAD_DELETE_FAILURE, this.updateById(updateRole));
        //删除角色权限
        delRoleMenu(roleId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assign(String roleId, List<String> menuIdList) {
        delRoleMenu(roleId);
        assignRole(roleId, menuIdList);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void assignRole(String roleId, List<String> menuIdList) {
        List<RoleMenu> roleMenuList = new ArrayList<>();
        for (String menuId : menuIdList) {
            RoleMenu rm = new RoleMenu();
            rm.setRoleId(roleId);
            rm.setMenuId(menuId);
            roleMenuList.add(rm);
        }
        if (CollectionUtils.isNotEmpty(roleMenuList)) {
            ApiAssert.isTrue(ErrorCodeEnum.INTERNAL_SERVER_ERROR.convert("授权失败"), roleMenuService.saveBatch(roleMenuList));
        }
    }

    @Override
    public void delRoleMenu(String roleId) {
        roleMenuService.remove(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId, roleId));
    }
}
